<?php
namespace app\resources\validate;
use think\Validate;
use think\facade\Request;
use think\exception\ValidateException;

class BaseValidate extends  Validate
{
	
    public function goCheck($scene = "")
    {
        //必须设置contetn-type:application/json
        $params = Request::instance()->param();
        if( ($params['mode'] ?? '') &&  ($params['data'] ?? '') ){
            $oid = $params['oid'] ?? '';
            $params = json_decode($params['data'],true)['data'];
            $params['id'] = $oid;
        }

        foreach(self::scene($scene)->rule as $key=>$rule){
            $key = explode('|', $key)[0];
            $params[$key] = $params[$key] ?? $rule;
        }

        try {
            $result = self::scene($scene)->check($params);
            if (!$result) {
                $error = self::geterror();
                $msg = is_array($error) ? implode(';', $error) : $error;
                throw new \think\exception\HttpException(415, $msg);
            }
            return $params;
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            throw new \think\exception\HttpException(415, $e->getError());
        }

    }

    /**
     * 正整数验证
     * @param $value
     * @param string $rule
     * @param string $data
     * @param string $field
     * @return bool|string
     */
    protected function isInteger($value, $rule='', $data='', $field='')
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        }
        return $field . '必须是正整数';
    }
}